write a query to n-th highest salary.
516
03-Jul-2024
Updated on 03-Jul-2024
Ravi Vishwakarma
03-Jul-2024To retrieve the n-th highest salary from a SQL Server table, you can use a similar approach to the previous query, but adjust the
ROW_NUMBER()function and filtering criteria. Here's how you can write a query to get the n-th highest salary:In this query:
Inner Query (
SalaryRanked): This subquery selects theSalarycolumn from your table (YourTableName) and assigns a row number (RowNum) to each row based on the descending order ofSalary.Outer Query: The outer query selects the
Salaryfrom theSalaryRankedsubquery where theRowNumequals@N.@Nis a parameter that you can adjust to retrieve the desired n-th highest salary. In the example above,@Nis set to3, so it will retrieve the third-highest salary.Adjust the
@Nvariable to fetch the n-th highest salary you're interested in from your table. This query will effectively fetch the specified n-th highest salary based on the sorting of theSalarycolumn in descending order.Read more
Write a query to get the second-highest salary.